<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>博客编辑页</title>

    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/edit.css">
    <link rel="stylesheet" href="css/components.css">
    <link rel="stylesheet" href="blog-editormd/css/editormd.css" />

</head>

<body>
<div class="nav">
    <div class="logo-container">
        <div class="logo-icon">B</div>
        <span class="blog-title">我的博客系统</span>
    </div>
    <div class="space"></div>
    <a class="nav-span" href="blog_list.html">主页</a>
    <a class="nav-span" href="blog_edit.html">写博客</a>
    <a class="nav-span" href="#" onclick="logout()">注销</a>
</div>
<div class="content-edit">
    <div class="push">
        <input type="hidden" id="blogId">
        <input type="text" name="title" id="title" placeholder="请输入博客标题" maxlength="100">
        <input type="button" value="更新文章" id="submit" onclick="updateBlog()">
    </div>
    <!-- markdown 插件 html代码 -->
    <div id="editor">
        <textarea style="display:none;" id="content">##在这里写下一篇博客</textarea>
    </div>
</div>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    // jQuery 加载失败的备用方案
    if (typeof jQuery === 'undefined') {
        document.write('<script src="blog-editormd/lib/jquery.min.js"><\/script>');
    }
</script>
<script src="blog-editormd/editormd.min.js"></script>
<script src="js/common.js"></script>
<script type="text/javascript">
    let editor; // 全局编辑器实例
    
    // 页面初始化
    $(document).ready(function() {
        // 检查登录状态
        const userId = localStorage.getItem("loginUserId");
        const token = localStorage.getItem("userToken");
        
        if (!userId || !token) {
            showMessage('请先登录', 'warning');
            setTimeout(() => {
                location.href = 'blog_login.html';
            }, 1500);
            return;
        }
        
        // 检查博客ID
        const urlParams = new URLSearchParams(location.search);
        const blogId = urlParams.get('blogId');
        if (!blogId) {
            showMessage('博客ID不存在', 'error');
            setTimeout(() => {
                location.href = 'blog_list.html';
            }, 1500);
            return;
        }
        
        // 获取博客信息
        getBlogInfo();
    });
    
    function initEditor(content = '') {
        try {
            editor = editormd("editor", {
                width: "100%",
                height: "550px",
                path: "blog-editormd/lib/",
                syncScrolling: "single",
                placeholder: "在这里编辑你的博客内容...",
                saveHTMLToTextarea: true,
                searchReplace: true,
                htmlDecode: "style,script,iframe|on*",
                emoji: true,
                taskList: true,
                tex: true,
                flowChart: true,
                sequenceDiagram: true,
                toolbar: true,
                lineNumbers: false,
                onload: function() {
                    this.watch();
                    if (content) {
                        this.setMarkdown(content);
                    }
                }
            });
        } catch (error) {
            console.error('编辑器初始化失败:', error);
            showMessage('编辑器加载失败，请刷新页面重试', 'error');
        }
    }

    function updateBlog() {
        // 获取表单数据
        const blogId = $("#blogId").val();
        const title = $("#title").val().trim();
        const content = editor ? editor.getMarkdown() : $("#content").val();
        
        // 前端验证
        if (!blogId) {
            showMessage('博客ID不存在', 'error');
            return;
        }
        
        if (!title) {
            showMessage('请输入博客标题', 'warning');
            $('#title').focus();
            return;
        }
        
        if (title.length > 100) {
            showMessage('标题长度不能超过100个字符', 'warning');
            $('#title').focus();
            return;
        }
        
        if (!content || content.trim() === '') {
            showMessage('请输入博客内容', 'warning');
            return;
        }
        
        if (content.length > 50000) {
            showMessage('博客内容过长，请缩短内容', 'warning');
            return;
        }
        
        // 显示加载状态
        showLoading("#submit", "更新中...");
        
        $.ajax({
            type: "post",
            url: "/blog/updateBlog",
            contentType: "application/json",
            data: JSON.stringify({
                id: blogId,
                title: title,
                content: content
            }),
            success: function(result) {
                hideLoading("#submit");
                
                if (result && result.code && result.code.toString() === "SUCCESS" && result.data === true) {
                    showMessage('博客更新成功！正在跳转...', 'success');
                    setTimeout(() => {
                        location.href = "blog_detail.html" + location.search;
                    }, 1000);
                } else {
                    showMessage(result.errMsg || '博客更新失败，请重试', 'error');
                }
            },
            error: function(xhr, status, error) {
                hideLoading("#submit");
                handleAjaxError(xhr, '博客更新失败，请重试');
            }
        });
    }
    
    function getBlogInfo() {
        showMessage('加载博客信息中...', 'info', 1000);
        
        $.ajax({
            type: "get",
            url: "/blog/getBlogDetail" + location.search,
            success: function(result) {
                if (result && result.code && result.code.toString() === "FAIL") {
                    showMessage(result.errMsg || '获取博客信息失败', 'error');
                    setTimeout(() => {
                        location.href = 'blog_list.html';
                    }, 2000);
                    return;
                }
                
                if (result && result.code && result.code.toString() === "SUCCESS" && result.data != null) {
                    const blogData = result.data;
                    
                    // 检查是否有编辑权限
                    const loginUserId = localStorage.getItem("loginUserId");
                    if (blogData.userId != loginUserId) {
                        showMessage('您没有权限编辑这篇博客', 'error');
                        setTimeout(() => {
                            location.href = 'blog_detail.html' + location.search;
                        }, 2000);
                        return;
                    }
                    
                    // 填充表单数据
                    $("#blogId").val(blogData.id);
                    $("#title").val(blogData.title || '');
                    
                    // 初始化编辑器并设置内容
                    initEditor(blogData.content || '');
                    
                    showMessage('博客信息加载完成', 'success', 1000);
                } else {
                    showMessage('获取博客信息失败', 'error');
                    setTimeout(() => {
                        location.href = 'blog_list.html';
                    }, 2000);
                }
            },
            error: function(xhr, status, error) {
                showMessage('加载博客信息失败，请刷新页面重试', 'error');
                console.error('获取博客信息失败:', error);
            }
        });
    }
    
    // 键盘快捷键
    $(document).keydown(function(e) {
        // Ctrl+S 保存
        if (e.ctrlKey && e.keyCode === 83) {
            e.preventDefault();
            updateBlog();
            return false;
        }
    });
</script>
</body>

</html>